import React, { useState, FC, useEffect } from "react";
import { useRef } from "react";
import "./index.css";

import Item from "./Item";

import { valueCheck, trimValue, Type } from "./utils";
import axios from "axios";
import { message } from "antd";

import { useNavigate } from "react-router-dom";
import service from "@/http/request";

const Register = ({ userInfo, callback }) => {
  const [inviteCode, setInviteCode] = useState({
    value: userInfo?.inviteCode || "",
    err: "",
  });
  const [username, setUsername] = useState({
    value: userInfo?.username || "",
    err: "",
  });
  const [email, setEmail] = useState({
    value: userInfo?.email || "",
    err: "",
  });
  const [password, setPassword] = useState({
    value: userInfo?.password || "",
    err: "",
  });
  const [confirmPassword, setConfirmPassword] = useState({
    value: userInfo?.confirmPassword || "",
    err: "",
  });
  const [emailCode, setEmailCode] = useState({
    value: userInfo?.emailCode || "",
    err: "",
  });

  const usernameChange = (e) => {
    const result = valueCheck(trimValue(e), Type.USERNAME);
    console.log(result);
    setUsername(result);
  };

  const passwordChange = (e) => {
    const result = valueCheck(trimValue(e), Type.PASSWORD);
    setPassword(result);
  };

  const confirmPasswordChange = (e) => {
    const result = valueCheck(
      trimValue(e),
      Type.CONFIRME_PASSWORD,
      password.value
    );
    setConfirmPassword(result);
  };

  const emailChange = (e) => {
    const result = valueCheck(trimValue(e), Type.EMAIL);
    setEmail(result);
  };

  const emailCodeChange = (e) => {
    const result = valueCheck(trimValue(e),Type.EMAIL_CODE);
    console.log(result)
    setEmailCode(result);
  };

  const onRegister = async () => {
    const data = {
      username: username.value,
      password: password.value,
      email: email.value,
      inviteCode: inviteCode,
      emailCode: emailCode.value,
    };
    // console.log(data);
    // console.log(emailCode);
    try {
      const result = await service.post("/users/register", data);
      console.log(result);
      message.success('注册成功')
      navigate('/user/login')
    } catch (e) {
      console.log(e);
    }
    
  };

  const [time, setTime] = useState(60);
  // 在组件顶部声明timerRef
  const timerRef = useRef();

  const disabledCode = useRef(false);

  const sendCode = async () => {
    if (email.value !== "") {
      disabledCode.current = true;

      timerRef.current = setInterval(() => {
        // 使用函数式更新确保拿到最新值
        setTime((prev) => {
          if (prev <= 1) {
            clearInterval(timerRef.current);
            disabledCode.current = false;
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      console.log(email);
      const result = await service.post("/users/sendEmailCode", {
        email: email.value,
      });
    } else {
      message.error("邮箱不能为空");
    }
  };

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => clearInterval(timerRef.current);
  }, []);

  const inviteCodeChange = (e) => {
    const result = trimValue(e);
    setInviteCode(result);
  };
  const navigate = useNavigate();

  const goBack = () => {
    window.history.go(-1);
  };

  return (
    <div className="homepage-form">
      <div className="title">注册信息</div>
      <div className="underline"></div>
      <Item label="用户名" required={true} error={username.err}>
        <input
          placeholder="请输入用户名..."
          defaultValue={username.value}
          type="text"
          onBlur={usernameChange}
        />
      </Item>

      <Item label="设置密码" required={true} error={password.err}>
        <input
          placeholder="请输入密码..."
          type="password"
          defaultValue={password.value}
          onBlur={passwordChange}
        />
      </Item>
      <Item label="再次输入密码" required={true} error={confirmPassword.err}>
        <input
          placeholder="请输入密码..."
          type="password"
          defaultValue={confirmPassword.value}
          onBlur={confirmPasswordChange}
        />
      </Item>
      <Item label="电子邮箱" required={true} error={email.err}>
        <input
          placeholder="请输入邮箱地址..."
          defaultValue={email.value}
          type="text"
          onBlur={emailChange}
        />
      </Item>
      <Item label="验证码" required={true} error={emailCode.err}>
        <div className="email-code">
          <input
            placeholder="请输入验证码"
            defaultValue={emailCode.value}
            type="text"
            onBlur={emailCodeChange}
          />

          <button
            className="email-code-button"
            onClick={sendCode}
            style={{
              marginLeft:20,
              width:120
            }}
            disabled={disabledCode.current}
          >
            {time > 0 && time < 60 ? `${time}秒后重试` : "发送验证码"}
          </button>
        </div>
      </Item>
      <Item label="邀请码" required={true} error={inviteCode.err}>
        <input
          placeholder="请输入邀请码"
          defaultValue={inviteCode.value}
          type="text"
          onBlur={inviteCodeChange}
        />
      </Item>
      <div className="button-container">
        <button type="submit" className="register-button" onClick={onRegister}>
          注册
        </button>
        <button type="submit" className="back-button" onClick={goBack}>
          返回
        </button>
      </div>
    </div>
  );
};

export default Register;
